package com.taptech.doufu.net.httputils;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.taptech.doufu.util.HttpRequestUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.weex.TFHttpCacheUtil;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.fragment.DiaobaoBaseFragment;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * <p>
 * Company: DiaoBao
 * </p>
 *
 * @author huangzh
 * @date 2014-3-17
 */
public class HttpUtil {

    public static final String data = "data";
    public static final String fail_code = "fail_code";
    public static final String user_msg = "user_msg";
    public static final String time_cost = "time_cost";
    public static final String status = "status";
    public static final String time_begin = "time_begin";
    public static final String handleType = "handleType";
    public static final String meta = "meta";

    public static void sendGetRequest(final HttpRequestObject request) {
        String url = Constant.HOST_NAME_SECOND + "/index.php/home/index";
        if (HttpRequestUtil.requests.contains(url)) {
            HttpRequestUtil.requests.remove(url);
        }
        if (HttpRequestUtil.requests.contains(request.getUrl()))
            return;

        new AsyncTask<Void, Void, JSONObject>() {
            long sendTim = System.currentTimeMillis();

            @Override
            protected JSONObject doInBackground(Void... params) {

                JSONObject jsonObj = null;
                try {
                    TTLog.s("requestURL::::::" + request.getUrl());
                    if (request.getSexType() != null && request.getSexType().equals("3")) {
                        ((WeMediaApplication) (WeMediaApplication.applicationContext)).sexType = "3";
                    } else if (request.getSexType() != null && request.getSexType().equals("1")) {
                        ((WeMediaApplication) (WeMediaApplication.applicationContext)).sexType = "1";
                    } else {

                    }
                    jsonObj = HttpRequestUtil.getJsonObjectFromServer(request.getUrl());
                } catch (Exception e) {
                    HttpRequestUtil.requests.remove(request.getUrl());
                    if (request.getListener() instanceof Activity) {
                        final HttpResponseObject res = new HttpResponseObject();
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        res.setReqURL(request.getUrl());
                        request.getListener().handleResponse(request.getHandleType(), res);
                        ((Activity) request.getListener()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                request.getListener().handleResponse(request.getHandleType(), res);
                            }
                        });
                    }
                    e.printStackTrace();
                }
                return jsonObj;
            }

            @Override
            protected void onPostExecute(JSONObject jsonObj) {
                try {
                    HttpResponseObject res = new HttpResponseObject();
                    res.setPageIndex(request.getPageIndex());
                    res.setHandleType(request.getHandleType());
                    res.setReqURL(request.getUrl());
                    if (jsonObj == null) {
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        request.getListener().handleResponse(res.getHandleType(), res);
                        return;
                    }
                    TTLog.s("http_response::::::" + request.getUrl());
                    TTLog.s("responseData:::::::" + jsonObj.toString(0));
                    long sendTim = System.currentTimeMillis();
                    res.setRequestData(request.getRequestData());
                    if (jsonObj.has(data)) {
                        res.setData(jsonObj.get(data));
                    }
                    if (jsonObj.has(fail_code)) {
                        res.setFail_code(jsonObj.getInt(fail_code));
                    }
                    if (jsonObj.has(status)) {
                        res.setStatus(jsonObj.getInt(status));
                    }
                    if (res.getStatus() == 34) {
                        if (request.getListener() != null && request.getListener() instanceof DiaobaoBaseActivity) {
                            request.getListener().handleResponse(res.getHandleType(), res);
                            ((DiaobaoBaseActivity) request.getListener()).presentWeexView("vue/personalcenter/TFBindMobileAlert.js?present=1");
                            return;
                        }
                    }
                    if (jsonObj.has(time_begin)) {
                        res.setTime_begin(jsonObj.getString(time_begin));
                    }
                    if (jsonObj.has(time_cost)) {
                        res.setTime_cost(jsonObj.getString(time_cost));
                    }
                    res.setUser_msg(DiaobaoUtil.getStringFromJSONObject(jsonObj, user_msg));
                    if (jsonObj.has(meta))
                        res.setMeta(jsonObj.getString(meta));
                    if (request.getListener() != null) {
                        Object dd = request.getListener();
                        request.getListener().handleResponse(res.getHandleType(), res);
                        if (request.getListener() instanceof DiaobaoBaseActivity) {//qlx
                            DiaobaoBaseActivity baseActivity = (DiaobaoBaseActivity) request.getListener();
                            baseActivity.reqestResCache.add(jsonObj);
                        } else if (request.getListener() instanceof DiaobaoBaseFragment) {
                            DiaobaoBaseFragment fragment = (DiaobaoBaseFragment) request.getListener();
                            fragment.requestsResCache.add(jsonObj);
                        }
                        TFHttpCacheUtil.cacheInNeed(jsonObj);//qlx
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            ;
        }.execute();
    }


    public static void sendLockedGetRequest(final HttpRequestObject request, final Activity activity) {

        if (HttpRequestUtil.requests.contains(request.getUrl()))
            return;

        new AsyncTask<Void, Void, JSONObject>() {
            long sendTim = System.currentTimeMillis();

            @Override
            protected JSONObject doInBackground(Void... params) {
                if (!HttpRequestUtil.requests.contains(request.getUrl()))
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UIUtil.showProgressDialog(activity);
                        }
                    });
                JSONObject jsonObj = null;
                try {
                    jsonObj = HttpRequestUtil.getJsonObjectFromServer(request.getUrl());
                } catch (Exception e) {
                    HttpRequestUtil.requests.remove(request.getUrl());
                    if (request.getListener() instanceof Activity) {
                        final HttpResponseObject res = new HttpResponseObject();
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        res.setReqURL(request.getUrl());
                        request.getListener().handleResponse(request.getHandleType(), res);
                        ((Activity) request.getListener()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                request.getListener().handleResponse(request.getHandleType(), res);
                            }
                        });
                    }
                    e.printStackTrace();
                }
                return jsonObj;
            }

            @Override
            protected void onPostExecute(JSONObject jsonObj) {
                try {
                    UIUtil.dismissDialog();
                    HttpResponseObject res = new HttpResponseObject();
                    res.setHandleType(request.getHandleType());
                    res.setPageIndex(request.getPageIndex());
                    res.setReqURL(request.getUrl());
                    if (jsonObj == null) {
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        request.getListener().handleResponse(res.getHandleType(), res);
                        return;
                    }
                    TTLog.s("http_response::::::" + request.getUrl());
                    //					TTLog.s("responseData:::::::" + jsonObj.toString(0));
                    res.setRequestData(request.getRequestData());
                    if (jsonObj.has(data)) {
                        res.setData(jsonObj.get(data));
                    }
                    if (jsonObj.has(fail_code)) {
                        res.setFail_code(jsonObj.getInt(fail_code));
                    }
                    if (jsonObj.has(status)) {
                        res.setStatus(jsonObj.getInt(status));
                    }
                    if (res.getStatus() == 34) {
                        if (request.getListener() != null && request.getListener() instanceof DiaobaoBaseActivity) {
                            request.getListener().handleResponse(res.getHandleType(), res);
                            ((DiaobaoBaseActivity) request.getListener()).presentWeexView("vue/personalcenter/TFBindMobileAlert.js?present=1");
                            return;
                        }
                    }
                    if (jsonObj.has(time_begin)) {
                        res.setTime_begin(jsonObj.getString(time_begin));
                    }
                    if (jsonObj.has(time_cost)) {
                        res.setTime_cost(jsonObj.getString(time_cost));
                    }
                    res.setUser_msg(DiaobaoUtil.getStringFromJSONObject(jsonObj, user_msg));
                    if (jsonObj.has(meta))
                        res.setMeta(jsonObj.getString(meta));
                    if (request.getListener() != null) {
                        request.getListener().handleResponse(res.getHandleType(), res);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                }
            }

            ;
        }.execute();
    }

    public static void sendPostRequest(final HttpRequestObject request) {

        if (HttpRequestUtil.requests.contains(request.getUrl()))
            return;

        new AsyncTask<Void, Void, JSONObject>() {
            long sendTim = System.currentTimeMillis();

            @Override
            protected JSONObject doInBackground(Void... params) {
                JSONObject jsonObj = null;
                try {
                    TTLog.s("requestURL::::::" + request.getUrl());
                    jsonObj = HttpRequestUtil.postToServer(request.getUrl(), request.getData());

                } catch (Exception e) {
                    HttpRequestUtil.requests.remove(request.getUrl());
                    if (request.getListener() instanceof Activity) {
                        final HttpResponseObject res = new HttpResponseObject();
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        res.setReqURL(request.getUrl());
                        request.getListener().handleResponse(res.getHandleType(), res);
                        ((Activity) request.getListener()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                request.getListener().handleResponse(request.getHandleType(), res);
                            }
                        });
                    }
                    e.printStackTrace();
                }
                return jsonObj;
            }

            @Override
            protected void onPostExecute(JSONObject jsonObj) {
                try {
                    HttpResponseObject res = new HttpResponseObject();
                    res.setReqURL(request.getUrl());
                    res.setHandleType(request.getHandleType());
                    if (jsonObj == null) {
                        // UIUtil.toastMessage(
                        // WeMediaApplication.applicationContext,
                        // "网络正在脑抽风，建议您先吃个麻辣烫");
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        if (request.getListener() != null) {
                            request.getListener().handleResponse(request.getHandleType(), res);
                        }
                        return;
                    }
                    TTLog.s("http_response::::::" + request.getUrl());
                    //					TTLog.s("responseData:::::::" + jsonObj.toString(0));
                    res.setRequestData(request.getRequestData());
                    res.setData(jsonObj.get(data));
                    if (jsonObj.has(fail_code)) {
                        res.setFail_code(jsonObj.getInt(fail_code));
                    }
                    if (jsonObj.has(status)) {
                        res.setStatus(jsonObj.getInt(status));
                    }
                    if (res.getStatus() == 34) {
                        if (request.getListener() != null && request.getListener() instanceof DiaobaoBaseActivity) {
                            request.getListener().handleResponse(res.getHandleType(), res);
                            ((DiaobaoBaseActivity) request.getListener()).presentWeexView("vue/personalcenter/TFBindMobileAlert.js?present=1");
                            return;
                        }
                    }
                    if (jsonObj.has(time_begin)) {
                        res.setTime_begin(jsonObj.getString(time_begin));
                    }
                    if (jsonObj.has(time_cost)) {
                        res.setTime_cost(jsonObj.getString(time_cost));
                    }
                    res.setUser_msg(DiaobaoUtil.getStringFromJSONObject(jsonObj, user_msg));
                    if (jsonObj.has(meta))
                        res.setMeta(jsonObj.getString(meta));
                    if (request.getListener() != null) {
                        request.getListener().handleResponse(res.getHandleType(), res);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IndexOutOfBoundsException e) {
                } catch (Exception e) {
                }

            }
        }.execute();
    }

    public static void sendLockedPostRequest(final HttpRequestObject request, final Activity activity) {
        if (HttpRequestUtil.requests.contains(request.getUrl()))
            return;
        new AsyncTask<Void, Void, JSONObject>() {
            long sendTim = System.currentTimeMillis();

            @Override
            protected JSONObject doInBackground(Void... params) {
                JSONObject jsonObj = null;
                if (!HttpRequestUtil.requests.contains(request.getUrl()))
                    if (activity != null) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                UIUtil.showProgressDialog(activity);
                            }
                        });
                    }
                try {
                    TTLog.s("requestURL::::::" + request.getUrl());
                    jsonObj = HttpRequestUtil.postToServer(request.getUrl(), request.getData());
                } catch (Exception e) {
                    HttpRequestUtil.requests.remove(request.getUrl());
                    if (request.getListener() instanceof Activity) {
                        final HttpResponseObject res = new HttpResponseObject();
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        res.setReqURL(request.getUrl());
                        request.getListener().handleResponse(request.getHandleType(), res);
                        ((Activity) request.getListener()).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                request.getListener().handleResponse(request.getHandleType(), res);
                            }
                        });

                    }
                    e.printStackTrace();
                }
                return jsonObj;
            }

            @Override
            protected void onPostExecute(JSONObject jsonObj) {
                try {
                    HttpResponseObject res = new HttpResponseObject();
                    res.setReqURL(request.getUrl());
                    res.setHandleType(request.getHandleType());
                    UIUtil.dismissDialog();
                    if (jsonObj == null) {
                        // UIUtil.toastMessage(
                        // WeMediaApplication.applicationContext,
                        // "网络正在脑抽风，建议您先吃个麻辣烫");
                        res.setStatus(Constant.STATUS_TIME_OUT);
                        request.getListener().handleResponse(res.getHandleType(), res);
                        return;
                    }
                    TTLog.s("http_response::::::" + request.getUrl());
                    //					TTLog.s("responseData:::::::" + jsonObj.toString(0));
                    res.setRequestData(request.getRequestData());
                    //res.setMessage(jsonObj.toString(0));
                    res.setData(jsonObj.get(data));
                    res.setFail_code(jsonObj.getInt(fail_code));
                    res.setStatus(jsonObj.getInt(status));
                    res.setTime_begin(jsonObj.getString(time_begin));
                    res.setTime_cost(jsonObj.getString(time_cost));
                    res.setUser_msg(DiaobaoUtil.getStringFromJSONObject(jsonObj, user_msg));
                    if (jsonObj.has(meta))
                        res.setMeta(jsonObj.getString(meta));
                    if (request.getListener() != null) {
                        request.getListener().handleResponse(res.getHandleType(), res);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                }
            }

            ;
        }.execute();
    }

    //int handleType, HttpResponseObject response

    public static interface HandleHttpResponListener {
        void handleRespon(int handleType, JSONObject data);
    }

    public static interface ErrorHttpResponListener {
        void handleRespon(int handleType, String errorTips);
    }

    public static void setOnHandleHttpResponListener(Context context, int handleType, HttpResponseObject response, HandleHttpResponListener listener) {
        if (response == null) {
            UIUtil.toastMessage(context, Constant.loadingFail);
            return;
        }
        if (response.getStatus() == Constant.STATUS_SUCCESS) {
            try {
                listener.handleRespon(handleType, (JSONObject) response.getData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (response.getUser_msg() != null) {
                UIUtil.toastMessage(context, response.getUser_msg());
            } else {
                UIUtil.toastMessage(context, Constant.loadingFail);
            }
        }
    }

    public static void setOnHandleHttpResponListener(Context context, int handleType, HttpResponseObject response, HandleHttpResponListener listener, ErrorHttpResponListener errorHttpResponListener) {
        if (response == null) {
            UIUtil.toastMessage(context, Constant.loadingFail);
            return;
        }
        if (response.getStatus() == Constant.STATUS_SUCCESS) {
            try {
                listener.handleRespon(handleType, (JSONObject) response.getData());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (response.getUser_msg() != null) {
                UIUtil.toastMessage(context, response.getUser_msg());
            } else {
                UIUtil.toastMessage(context, Constant.loadingFail);
            }
            errorHttpResponListener.handleRespon(handleType, response.getUser_msg());
        }
    }
}
